<?php

namespace app\api\controller;

use think\Db;

if (!function_exists('getallheaders')) {
    function getallheaders() {
        $headers = array();
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}

class Client extends Base
{

	public function _initialize() {
        parent::_initialize();
        $headers = getallheaders();
		if($headers['Token'] != $this->token()){
			header('Content-Type:application/json; charset=utf-8');
			exit(json_encode([
				'status' => 0,
				'msg' => '非法操作'
			],JSON_UNESCAPED_UNICODE));
		}
    }

	public function get_server(){
		$data['os'] = PHP_OS;
		$data['ip'] = $_SERVER['SERVER_ADDR'] . ':' . $_SERVER['SERVER_PORT'];
		$data['php_sapi_name'] = php_sapi_name();
		$data['php_version'] = PHP_VERSION;
		$data['upload_max_filesize'] = ini_get('upload_max_filesize');
		$data['max_execution_time'] = ini_get('max_execution_time') . "秒";
		$data['memory_limit'] = ini_get('memory_limit');
		$data['disk_free_space'] = round((@disk_free_space(".") / (1024 * 1024)), 2) . 'M';
		$data['server_time'] = date("Y年n月j日 H:i:s");
		return json([
			'status' => 1,
			'msg' => '执行成功',
			'data' => $data 
		]);
	}

	public function put_pic(){
		$domain = 'https://nrk.17shangji.com';
		$arcid = input('get.arcid/d',0);
		$modid = input('get.modid/d',0);
		if(empty($arcid) || empty($modid) || empty($domain)){
			return json([
				'status' => 0,
				'msg' => '参数错误'
			]);
		}
		$mod = Db::name('channeltype')->field('id,table')->find($modid);
		if(empty($mod)){
			return json([
				'status' => 0,
				'msg' => '模块为空'
			]);
		}
		$table = 'archives';
		$tableExt = $mod['table'].'_content';
		$dataExt = Db::name($tableExt)->field('id,content')->where('aid',$arcid)->find();
		if(empty($dataExt['content'])){
			return json([
				'status' => 0,
				'msg' => '内容为空'
			]);
		}
		$pattern = "/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]))[\'|\"].*?[\/]?>/";
    	preg_match_all($pattern,$dataExt['content'],$match); 
    	if(!empty($match[1])){
			$litpic = '';
			foreach ($match[1] as $k => $v) {
    			if(strpos($v, 'http') === false){
    				$url = $domain.str_replace('/uploads', '', $v);
    				$pic = $this->grabImage($url);
    				if(empty($litpic)){
    					$litpic = $pic;
    				}
    				$dataExt['content'] = str_replace($v, $pic, $dataExt['content']);
    			}
    		}
    		Db::name($tableExt)->where('id',$dataExt['id'])->update([
    			'content' => $dataExt['content'],
    		]);
    		if(!empty($litpic)){
    			Db::name($table)->where('aid',$arcid)->update([
    				'litpic' => $litpic,
    				'is_litpic' => 1
    			]);
    		}
		}
		return json([
			'status' => 1,
			'msg' => '执行成功'
		]);
	}

	private function token(){
		$date = date('Y.m.d.H',time());
		$token = md5(md5($date.'xiexueyuan.com'));
		return $token;
	}

	private function grabImage($url, $filename = "") {
		if ($url == "") return false;
		if ($filename == "") {
			$ext = strrchr($url, ".");
			if ($ext != ".png" && $ext != ".gif" && $ext != ".jpg" && $ext != ".jpeg") return false;
			$filename = md5(mt_rand(0,9999).time().mt_rand(0,9999)).$ext;
		} 
		$filepath = '/uploads/allimg/'.date('Ymd').'/';
		if(!is_dir(ROOT_PATH.$filepath)){
			mkdir(ROOT_PATH.$filepath,0777,true);
		}
		ob_start();//打开输出
		readfile($url);//输出图片文件
		$img = ob_get_contents();//得到浏览器输出
		ob_end_clean();//清除输出并关闭
		// $size = strlen($img);//得到图片大小
		$fp = @fopen(ROOT_PATH.$filepath.$filename, "a");
		fwrite($fp, $img);//向当前目录写入图片文件，并重新命名
		fclose($fp);
		// $this->compressed_image(ROOT_PATH.$filepath.$filename,ROOT_PATH.$filepath.$filename);
		return $filepath.$filename;//返回新的文件名
	} 

	/**
   * desription 判断是否gif动画
   * @param sting $image_file图片路径
   * @return boolean t 是 f 否
   */
	private function check_gifcartoon($image_file){
		$fp = fopen($image_file,'rb');
		$image_head = fread($fp,1024);
		fclose($fp);
		return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)?false:true;
	}

	/**
	* desription 压缩图片
	* @param sting $imgsrc 图片路径
	* @param string $imgdst 压缩后保存路径
	*/
	private function compressed_image($imgsrc,$imgdst){
		list($width,$height,$type)=getimagesize($imgsrc);
		$new_width = ($width>600?600:$width)*0.9;
		$new_height =($height>600?600:$height)*0.9;
		switch($type){
		  	case 1:
			    $giftype = $this->check_gifcartoon($imgsrc);
			    if($giftype){
					header('Content-Type:image/gif');
					$image_wp=imagecreatetruecolor($new_width, $new_height);
					$image = imagecreatefromgif($imgsrc);
					imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
					//75代表的是质量、压缩图片容量大小
					imagejpeg($image_wp, $imgdst,75);
					imagedestroy($image_wp);
			    }
		    break;
		  	case 2:
				header('Content-Type:image/jpeg');
				$image_wp=imagecreatetruecolor($new_width, $new_height);
				$image = imagecreatefromjpeg($imgsrc);
				imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
				//75代表的是质量、压缩图片容量大小
				imagejpeg($image_wp, $imgdst,75);
				imagedestroy($image_wp);
		    break;
		  	case 3:
			    header('Content-Type:image/png');
			    $image_wp=imagecreatetruecolor($new_width, $new_height);
			    $image = imagecreatefrompng($imgsrc);
			    imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
			    //75代表的是质量、压缩图片容量大小
			    imagejpeg($image_wp, $imgdst,75);
			    imagedestroy($image_wp);
		    break;
		}
	}


}